package fancy.calendar.database;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Database connection class to get database connection.<br/>
 * Configure database connection parameters in 'setting.properties' under the
 * same package.
 * 
 * @author wannadream
 * 
 */
public class DBConnection {

	private Properties dbProps;

	/**
	 * Initialize the db connection parameters
	 * 
	 * @throws IOException
	 */
	public DBConnection() throws IOException {
		this.dbProps = new Properties();
		InputStream in = getClass().getResourceAsStream("setting.properties");
		dbProps.load(in);
		in.close();
	}

	/**
	 * Return db connection
	 * 
	 * @return
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	public Connection getConnection() throws SQLException,
			ClassNotFoundException {

		Connection conn = null;
		Properties connectionProps = new Properties();
		connectionProps.put("user",
				this.dbProps.getProperty("database.username"));
		connectionProps.put("password",
				this.dbProps.getProperty("database.password"));

		Class.forName(this.dbProps.getProperty("database.classname"));
		conn = DriverManager.getConnection(
				"jdbc:" + this.dbProps.getProperty("database.dbms") + "://"
						+ this.dbProps.getProperty("database.server") + ":"
						+ this.dbProps.getProperty("database.port") + "/"
						+ this.dbProps.getProperty("database.name"),
				connectionProps);
		return conn;
	}
}
